package com.bitcointoolkit.common.cash;

import com.bitcointoolkit.common.cash.param.AbstractChainParams;

/**
 * 公钥
 *
 * @author caican
 * @date 18/6/19
 */
public class PubKey {
    private byte[] key;

    private byte[] hash;

    private String legacy;

    private String cashAddr;

    private final static BechCashUtil CASH = BechCashUtil.getInstance();

    public PubKey(byte[] bytes) {
        getLen(bytes);
        key = bytes.clone();

        hash = CipherUtils.pubKeyHash160(key);

        legacy = CASH.pubKeyHashToLegacy(getPubKeyHash());

        cashAddr = CASH.transferLegacyToCashAddr(legacy);
    }

    public PubKey(byte[] bytes, AbstractChainParams params) {
        getLen(bytes);
        key = bytes.clone();

        hash = CipherUtils.pubKeyHash160(key);

        legacy = CASH.pubKeyHashToLegacy(getPubKeyHash(), params);

        try {
            cashAddr = CASH.transferLegacyToCashAddr(legacy);
        } catch (Exception e) {

        }
    }

    private int getLen(byte[] bytes) {
        if (bytes.length != 33 && bytes.length != 65) {
            throw new RuntimeException("公钥必须是33 或 65 字节");
        }
        byte chHeader = bytes[0];
        if (chHeader == 2 || chHeader == 3) { return 33;}
        if (chHeader == 4 || chHeader == 6 || chHeader == 7) { return 65;}
        throw new RuntimeException("公钥非法");
    }

    public int size() {
        return key.length;
    }

    /**
     * 获取公钥hash
     */
    public byte[] getPubKeyHash() {
        return hash.clone();
    }

    /** 获取地址
     * @param isLegacy 是否返回Legacy格式
     * @return 地址
     */
    public String getAddress(boolean isLegacy) {
        if (isLegacy) {
            return legacy;
        }
        return cashAddr;
    }

}
